"""
任务存储管理器
负责持久化保存任务状态和历史记录
"""

import json
import logging
import os
import threading
from typing import Dict, List, Any, Optional
from datetime import datetime


class TaskStorage:
    """任务存储管理器"""
    
    def __init__(self, storage_file: str = "data/task_history.json"):
        self.storage_file = storage_file
        self.logger = logging.getLogger(__name__)
        self.lock = threading.RLock()
        
        # 确保数据目录存在
        os.makedirs(os.path.dirname(storage_file), exist_ok=True)
        
        # 内存中的任务状态
        self.task_status: Dict[str, Dict] = {}
        
        # 加载现有数据
        self._load_tasks()
    
    def _load_tasks(self):
        """从文件加载任务数据"""
        try:
            if os.path.exists(self.storage_file):
                with open(self.storage_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.task_status = data.get('task_status', {})
                    self.logger.info(f"加载了 {len(self.task_status)} 个历史任务")
            else:
                self.task_status = {}
                self.logger.info("未找到历史任务文件，创建新的任务存储")
        
        except Exception as e:
            self.logger.error(f"加载任务数据失败: {str(e)}")
            self.task_status = {}
    
    def _save_tasks(self):
        """保存任务数据到文件"""
        try:
            with self.lock:
                data = {
                    'task_status': self.task_status,
                    'last_updated': datetime.now().isoformat()
                }
                
                # 原子性写入
                temp_file = self.storage_file + '.tmp'
                with open(temp_file, 'w', encoding='utf-8') as f:
                    json.dump(data, f, ensure_ascii=False, indent=2)
                
                # 替换原文件
                if os.path.exists(self.storage_file):
                    os.remove(self.storage_file)
                os.rename(temp_file, self.storage_file)
                
        except Exception as e:
            self.logger.error(f"保存任务数据失败: {str(e)}")
    
    def add_task(self, task_id: str, task_data: Dict[str, Any]):
        """添加新任务"""
        with self.lock:
            self.task_status[task_id] = task_data
            self._save_tasks()
    
    def update_task(self, task_id: str, updates: Dict[str, Any]):
        """更新任务状态"""
        with self.lock:
            if task_id in self.task_status:
                self.task_status[task_id].update(updates)
                self._save_tasks()
    
    def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:
        """获取单个任务"""
        with self.lock:
            return self.task_status.get(task_id)
    
    def get_all_tasks(self) -> List[Dict[str, Any]]:
        """获取所有任务"""
        with self.lock:
            return list(self.task_status.values())
    
    def get_recent_tasks(self, limit: int = 10) -> List[Dict[str, Any]]:
        """获取最近的任务"""
        with self.lock:
            tasks = list(self.task_status.values())
            # 按开始时间排序
            tasks.sort(key=lambda x: x.get('start_time', ''), reverse=True)
            return tasks[:limit]
    
    def delete_task(self, task_id: str) -> bool:
        """删除任务"""
        with self.lock:
            if task_id in self.task_status:
                del self.task_status[task_id]
                self._save_tasks()
                return True
            return False
    
    def cleanup_old_tasks(self, max_tasks: int = 100):
        """清理过多的历史任务，保留最新的指定数量"""
        with self.lock:
            if len(self.task_status) > max_tasks:
                # 按时间排序，保留最新的
                tasks = list(self.task_status.items())
                tasks.sort(key=lambda x: x[1].get('start_time', ''), reverse=True)
                
                # 删除多余的任务
                tasks_to_keep = dict(tasks[:max_tasks])
                self.task_status = tasks_to_keep
                self._save_tasks()
                
                self.logger.info(f"清理了历史任务，保留最新的 {max_tasks} 个")
    
    def get_task_statistics(self) -> Dict[str, Any]:
        """获取任务统计信息"""
        with self.lock:
            total_tasks = len(self.task_status)
            completed_tasks = sum(1 for task in self.task_status.values() 
                                if task.get('status') == 'completed')
            failed_tasks = sum(1 for task in self.task_status.values() 
                             if task.get('status') == 'failed')
            
            return {
                'total_tasks': total_tasks,
                'completed_tasks': completed_tasks,
                'failed_tasks': failed_tasks,
                'success_rate': (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
            }


# 全局任务存储实例
task_storage = TaskStorage()